package com.xinchuang.service.targetSystem.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinchuang.common.KeyWordSystem;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultEnum;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.entity.target.TargetCommonAttribute;
import com.xinchuang.entity.targetSystem.FontTable;
import com.xinchuang.entity.targetSystem.RangeType;
import com.xinchuang.mapper.target.TargetCommonAttributeMapper;
import com.xinchuang.mapper.targetSystem.*;
import com.xinchuang.mapper.targetSystem.external.TargetExternalMapper;
import com.xinchuang.entity.targetSystem.Region;
import com.xinchuang.entity.targetSystem.Zone;
import com.xinchuang.entity.targetSystem.object.CommonAdd;
import com.xinchuang.entity.targetSystem.system.CommonAttribute;
import com.xinchuang.entity.targetSystem.system.TargetType;
import com.xinchuang.entity.targetSystem.target.TargetData;
import com.xinchuang.service.RedisUseService;
import com.xinchuang.service.target.TargetCommonAttributeService;
import com.xinchuang.service.targetSystem.CommonService;
import com.xinchuang.service.targetSystem.      FontTableService;
import com.xinchuang.service.targetSystem.KnowService;
import com.xinchuang.util.FileElseUtil;
import com.xinchuang.util.RedisUtil;
import com.xinchuang.util.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @ClassName CommonServiceImpl
 * @Description: TODO(共有属性服务实现)
 * @Author zhangxuan
 * @Date 2021-03-30 18:08
 * @Verion V1.0
 */
@Slf4j
@Service(value = "commonService")
public class CommonServiceImpl implements CommonService {

    @Resource
    private CommonMapper commonMapper;

    @Resource
    private TargetMapper targetMapper;

    @Resource
    private ZoneMapper zoneMapper;

    @Resource
    private RegionMapper regionMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private KeyWordSystem keyWordSystem;

    private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1, 1);

    @Resource
    private TargetExternalMapper targetExternalMapper;

    @Resource
    private RedisUseService redisUseService;

    @Resource
    private RangeTypeMapper rangeTypeMapper;

    @Resource
    private FontTableService fontTableService;

    @Resource
    private TargetCommonAttributeMapper targetCommonAttributeMapper;

    /**
     * 主目标共有字段名称redis存储key
     */
    private final String main_common_key = "common_main_key";
    /**
     * 主目标共有属性名称redis存储key
     */
    private final String main_common_key_name = "common_main_key_name";
    /**
     * 主目标共有属性名称redis存储key
     */
    private final String sub_common_key = "common_sub_key";
    /**
     * 主目标共有字段名称redis存储key
     */
    private final String sub_common_key_name = "common_sub_key_name";

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result addCommon(CommonAdd commonAdd) {
        if (null == commonAdd.getSign() || (commonAdd.getSign() < 1 || commonAdd.getSign() > 2)) {
            return ResultUtil.error(ResultEnum.SIGN_ERROR);
        }
        if (judgeParamName(commonAdd.getKey()) || commonAdd.getKey().equals("desicribe")) {
            return ResultUtil.error(500, commonAdd.getKey() + "字段名称是系统专有属性，请重新命名");
        }
        Set<Object> keySet = null;
        String key = keyWordSystem.getVERSION() + (commonAdd.getSign() == 1 ? main_common_key : sub_common_key);
        String keyName = keyWordSystem.getVERSION() + (commonAdd.getSign() == 1 ? main_common_key_name : sub_common_key_name);
        Set<Object> keyNameSet = null;
        if (redisUtil.hasKey(key)) {
            if (redisUtil.sHasKey(key, commonAdd.getKey())) {
                return ResultUtil.error(ResultEnum.COMMON_KEY_EXIST);
            }
            keySet = redisUtil.sGet(key);
        } else {
            keySet = new HashSet<>();
        }
        if (redisUtil.hasKey(keyName)) {
            if (redisUtil.sHasKey(keyName, commonAdd.getKeyName())) {
                return ResultUtil.error(ResultEnum.COMMON_KEY_NAME_EXIST);
            }
            keyNameSet = redisUtil.sGet(keyName);
        } else {
            keyNameSet = new HashSet<>();
        }
        commonAdd.setId(snowflakeIdWorker.nextId() + "");
        commonAdd.setSign(commonAdd.getSign());
        CommonAttribute attribute = FileElseUtil.getCommonAttributeByAdd(commonAdd);
        Integer sort = commonMapper.getCommonMaxSort(commonAdd.getSign());
        attribute.setSort(sort + 1);
        commonMapper.addCommon(attribute);
        keySet.add(commonAdd.getKey());
        keyNameSet.add(commonAdd.getKeyName());
        redisUtil.sSet(key, keySet.toArray());
        redisUtil.sSet(keyName, keyNameSet.toArray());
        return ResultUtil.success("新增成功", null);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result delCommon(String id) {
        CommonAttribute commonAttribute = commonMapper.findOneCommonById(id);
        if (null == commonAttribute) {
            return ResultUtil.error(ResultEnum.COMMON_EMPTY);
        }
        if (judgeParamName(commonAttribute.getKey()) || commonAttribute.getKey().equals("desicribe")) {
            return ResultUtil.error(ResultEnum.SYSTEM_COMMOM_IS_NOT_DELETE);
        }
        String key = keyWordSystem.getVERSION() + (commonAttribute.getSign() == 1 ? main_common_key : sub_common_key);
        String keyName = keyWordSystem.getVERSION() + (commonAttribute.getSign() == 1 ? main_common_key_name : sub_common_key_name);
        commonMapper.deleteCommon(id);
        redisUtil.setRemove(key, commonAttribute.getKey());
        redisUtil.setRemove(keyName, commonAttribute.getKeyName());
        return ResultUtil.success("删除成功", null);
    }

    @Override
    public Result updateCommon(CommonAdd commonAdd) {
        if (StringUtils.isBlank(commonAdd.getId())) {
            return ResultUtil.error(ResultEnum.UPDATE_EMPTY);
        }
        CommonAttribute old = commonMapper.findOneCommonById(commonAdd.getId());
        if (null == old) {
            return ResultUtil.error(ResultEnum.COMMON_EMPTY);
        } else {
            if (old.getKey().equals("desicribe") && !commonAdd.getKey().equals("desicribe")) {
                return ResultUtil.error(500, commonAdd.getKey() + "字段名称是系统专有属性，不可被修改");
            }
        }
        if (judgeParamName(commonAdd.getKey())) {
            return ResultUtil.error(500, commonAdd.getKey() + "字段名称是系统专有属性，请重新命名");
        }
        String key = keyWordSystem.getVERSION() + (old.getSign() == 1 ? main_common_key : sub_common_key);
        String keyName = keyWordSystem.getVERSION() + (old.getSign() == 1 ? main_common_key_name : sub_common_key_name);
        commonAdd.setKey(old.getKey());
        /**
         if (!commonAdd.getKey().equals(old.getKey())) {
         if (redisUtil.sHasKey(key, commonAdd.getKey())) {
         return ResultUtil.error(ResultEnum.COMMON_KEY_EXIST);
         } else {
         redisUtil.setRemove(key, old.getKey());
         }
         if (commonAdd.getSign() == 1) {
         knowService.updateKnowIndexAndRemark(old.getKey(), commonAdd.getKey(), 1, 1, null);
         } else {
         knowService.updateKnowIndexAndRemark(old.getKey(), commonAdd.getKey(), 1, 2, null);
         }
         }
         **/
        if (!commonAdd.getKeyName().equals(old.getKeyName())) {
            if (redisUtil.sHasKey(keyName, commonAdd.getKeyName())) {
                return ResultUtil.error(ResultEnum.COMMON_KEY_NAME_EXIST);
            } else {
                redisUtil.setRemove(keyName, old.getKeyName());
            }
        }
        commonMapper.updateCommon(FileElseUtil.getCommonAttributeByAdd(commonAdd));
        Set<Object> keySet = redisUtil.sGet(key);
        Set<Object> keyNameSet = redisUtil.sGet(keyName);
        keySet.add(commonAdd.getKey());
        keyNameSet.add(commonAdd.getKeyName());
        redisUtil.sSet(key, keySet.toArray());
        redisUtil.sSet(keyName, keyNameSet.toArray());
        return ResultUtil.success("更新成功", null);
    }

    @Override
    public void initializeCommonMainData() {
        CommonAttribute attribute = new CommonAttribute();
        CommonAttribute common = commonMapper.findOneCommonById("001");
        if (ObjectUtil.isNull(common)) {
            attribute.setId("001");
            attribute.setKeyName("描述");
            attribute.setKey("desicribe");
            attribute.setKeyType("String");
            attribute.setShowType("textarea");
            attribute.setRequired("true");
            attribute.setInfo("false");
            attribute.setVerify("true");
            attribute.setEnumerator("[]");
            attribute.setRow("5");
            attribute.setSign(1);
            attribute.setMessage("{targetName}位于{country}{country-orientation},{lon},{lat},{distance-orientation},是{country}重要的{targetClassify}之一,{targetName}{dixing}若被摧毁，将对{country}{targetClassify}相应军队作战能力造成重大影响。{targetName}占地面积{area},{sub-message}");
            attribute.setSort(1);
            commonMapper.insert(attribute);
        }
        common = commonMapper.findOneCommonById("002");
        if (ObjectUtil.isNull(common)) {
            attribute.setId("002");
            attribute.setKeyName("描述");
            attribute.setKey("desicribe");
            attribute.setKeyType("String");
            attribute.setShowType("textarea");
            attribute.setRequired("true");
            attribute.setInfo("false");
            attribute.setVerify("true");
            attribute.setEnumerator("[]");
            attribute.setRow("5");
            attribute.setSign(2);
            attribute.setMessage("{targetName}：位于{main-orientation}，长{longth}，宽{breath}，面积{area}，海拔高{height}米，{lon}，{lat}，材质是{material}。");
            attribute.setSort(1);
            commonMapper.insert(attribute);
        }
//        common = commonMapper.findOneCommonById("003");
//        if (null == common) {
//            attribute.setId("003");
//            attribute.setKeyName("要害能力指标值");
//            attribute.setKey("crucial");
//            attribute.setKeyType("Double");
//            attribute.setShowType("text");
//            attribute.setRequired("true");
//            attribute.setInfo("true");
//            attribute.setVerify("true");
//            attribute.setMin("0");
//            attribute.setMax("100");
//            attribute.setEnumerator("[]");
//            attribute.setRow(null);
//            attribute.setSign(2);
//            attribute.setMessage("请输入要害能力值");
//            attribute.setSort(2);
//            commonMapper.addReplaceCommon(attribute);
//        }
        //初始化排序
        if (null != common && null == common.getSort()) {
            try {
                List<CommonAttribute> commons = commonMapper.findCommonSortSign(1);
                CommonAttribute commonAttribute = null;
                int sign = 2;
                for (int i = 0; i < commons.size(); i++) {
                    commonAttribute = commons.get(i);
                    if (commonAttribute.getId().equals("001")) {
                        commonMapper.updateCommonSort("001", 1);
                    } else {
                        commonMapper.updateCommonSort(commonAttribute.getId(), sign);
                        sign++;
                    }
                }
                commons = commonMapper.findCommons(2);
                sign = 3;
                for (int i = 0; i < commons.size(); i++) {
                    commonAttribute = commons.get(i);
                    if (commonAttribute.getId().equals("002")) {
                        commonMapper.updateCommonSort("002", 1);
                    } else if (commonAttribute.getId().equals("003")) {
                        commonMapper.updateCommonSort("003", 2);
                    } else {
                        commonMapper.updateCommonSort(commonAttribute.getId(), sign);
                        sign++;
                    }
                }
            } catch (Exception e) {

            }
        }
        if (redisUtil.hasKey(keyWordSystem.getVERSION() + main_common_key)) {
            redisUtil.del(keyWordSystem.getVERSION() + main_common_key);
        }
        if (redisUtil.hasKey(keyWordSystem.getVERSION() + main_common_key_name)) {
            redisUtil.del(keyWordSystem.getVERSION() + main_common_key_name);
        }
        List<CommonAttribute> main = commonMapper.findCommons(1);
        if (null != main && !main.isEmpty()) {
            Set<Object> keySet = new HashSet<>();
            Set<Object> keyNameSet = new HashSet<>();
            for (CommonAttribute commonAttribute : main) {
                keySet.add(commonAttribute.getKey());
                keyNameSet.add(commonAttribute.getKeyName());
                redisUtil.sSet(keyWordSystem.getVERSION() + main_common_key, keySet.toArray());
                redisUtil.sSet(keyWordSystem.getVERSION() + main_common_key_name, keyNameSet.toArray());
            }
        }
    }

    @Override
    public void initializeCommonSubData() {
        if (redisUtil.hasKey(keyWordSystem.getVERSION() + sub_common_key)) {
            redisUtil.del(keyWordSystem.getVERSION() + sub_common_key);
        }
        if (redisUtil.hasKey(keyWordSystem.getVERSION() + sub_common_key_name)) {
            redisUtil.del(keyWordSystem.getVERSION() + sub_common_key_name);
        }
        List<CommonAttribute> sub = commonMapper.findCommons(2);
        if (null != sub && !sub.isEmpty()) {
            Set<Object> keySet = new HashSet<>();
            Set<Object> keyNameSet = new HashSet<>();
            for (CommonAttribute commonAttribute : sub) {
                keySet.add(commonAttribute.getKey());
                keyNameSet.add(commonAttribute.getKeyName());
                redisUtil.sSet(keyWordSystem.getVERSION() + sub_common_key, keySet.toArray());
                redisUtil.sSet(keyWordSystem.getVERSION() + sub_common_key_name, keyNameSet.toArray());
            }
        }
    }

    @Override
    public Result selectCommonList(Integer pageNum, Integer pageSize, String status) {
        if (pageNum == null || pageSize == null) {
            List<CommonAttribute> commonAttributes = null;
            if (status.contains("main")) {
                commonAttributes = commonMapper.findCommons(1);
            } else {
                commonAttributes = commonMapper.findCommons(2);
            }
            Map<String, Object> resultMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(commonAttributes)) {
                List<Map<String, Object>> list = new ArrayList<>();
                mainCommon(list);
                for (CommonAttribute commonAttribute : commonAttributes) {
                    if (commonAttribute.getKey().equals("desicribe")) {
                        continue;
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", commonAttribute.getId());
                    map.put("keyName", commonAttribute.getKeyName());
                    map.put("key", commonAttribute.getKey());
                    map.put("keyType", commonAttribute.getKeyType());
                    map.put("showType", commonAttribute.getShowType());
                    map.put("required", commonAttribute.getRequired());
                    map.put("info", commonAttribute.getInfo());
                    map.put("dataRange", commonAttribute.getDataRange());
                    map.put("verify", commonAttribute.getVerify());
                    map.put("min", commonAttribute.getMin());
                    map.put("max", commonAttribute.getMax());
                    map.put("enumerator", FileElseUtil.getStringTransitionList(commonAttribute.getEnumerator()));
                    map.put("row", commonAttribute.getRow());
                    map.put("message", commonAttribute.getMessage());
                    list.add(map);
                }
                resultMap.put("commonList", list);
                return ResultUtil.success("查询成功", resultMap);
            }
            resultMap.put("commonList", new ArrayList<>());
            return ResultUtil.success("查询成功", resultMap);
        }
        LambdaQueryWrapper<TargetCommonAttribute> wrapper = new LambdaQueryWrapper<>();
        if (status.contains("main")) {
            wrapper.eq(TargetCommonAttribute::getSign, 1);
        } else {
            wrapper.eq(TargetCommonAttribute::getSign, 2);
        }
        wrapper.orderByAsc(TargetCommonAttribute::getSort);
        Page<TargetCommonAttribute> commonAttributes = targetCommonAttributeMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        Map<String, Object> resultMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(commonAttributes.getRecords())) {
            List<Map<String, Object>> list = new ArrayList<>();
            for (TargetCommonAttribute commonAttribute : commonAttributes.getRecords()) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", commonAttribute.getId());
                map.put("keyName", commonAttribute.getKeyName());
                map.put("key", commonAttribute.getKeyValue());
                map.put("keyType", commonAttribute.getKeyType());
                map.put("showType", commonAttribute.getShowType());
                map.put("required", commonAttribute.getRequired());
                map.put("info", commonAttribute.getInfo());
                map.put("dataRange", commonAttribute.getDataRange());
                map.put("verify", commonAttribute.getVerify());
                map.put("min", commonAttribute.getMin());
                map.put("max", commonAttribute.getMax());
                map.put("enumerator", FileElseUtil.getStringTransitionList(commonAttribute.getEnumerator()));
                map.put("row", commonAttribute.getRowValue());
                map.put("message", commonAttribute.getMessage());
                list.add(map);
            }
            resultMap.put("commonList", list);
        } else {
            resultMap.put("commonList", new ArrayList<>());
        }
        resultMap.put("pageNum", commonAttributes.getCurrent());
        resultMap.put("pageSize", commonAttributes.getSize());
        resultMap.put("total", commonAttributes.getTotal());
        resultMap.put("pageAll", commonAttributes.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    public Result selectSignData(String status) {
        if (status.equals("country")) {
            List<Object> countrys = redisUtil.lGet(keyWordSystem.getVERSION() + "country", 0, -1);
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (Object o : countrys) {
                Map<String, Object> map = new HashMap<>();
                map.put("value", 0);
                map.put("label", o);
                resultList.add(map);
            }
            return ResultUtil.success("查询成功", resultList);
        } else if (status.equals("classify")) {
            List<TargetType> list = targetExternalMapper.selectTypeByLevel(1);
            List<Map<String, Object>> resultList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(list)) {
                for (TargetType targetType : list) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", targetType.getTypeId());
                    map.put("value", targetType.getTypeName());
                    resultList.add(map);
                }
            }
            return ResultUtil.success("查询成功", resultList);
        } else if (status.equals("common")) {
            Map<String, Object> resultMap = new HashMap<>();
            Map<Object, Object> hmget = redisUtil.hmget(this.keyWordSystem.getVERSION() + "-COMMON-SORT");
            if (CollectionUtil.isNotEmpty(hmget)) {
                List<Map.Entry<Object, Object>> list = new ArrayList<Map.Entry<Object, Object>>(hmget.entrySet());
                Collections.sort(list, new Comparator<Map.Entry<Object, Object>>() {
                    @Override
                    public int compare(Map.Entry<Object, Object> o1, Map.Entry<Object, Object> o2) {
                        int key1 = Integer.parseInt(o1.getValue().toString());
                        int key2 = Integer.parseInt(o2.getValue().toString());
                        if (key1 == key2) {
                            return 0;
                        } else {
                            return key1 < key2 ? 1 : -1;
                        }
                    }
                });
                List<Map<String, Object>> resultList = new ArrayList<>();
                Map<String, Object> map = null;
                for (int i = 0, j = list.size(); i < j; i++) {
                    if (i > 9) {
                        break;
                    }
                    Map.Entry<Object, Object> entry = list.get(i);
                    map = new HashMap<>();
                    TargetData only = targetMapper.findTargetOnly(entry.getKey().toString());
                    if (null != only) {
                        map.put("targetId", only.getTargetId());
                        map.put("targetName", only.getTargetName());
                        map.put("targetClassify", only.getTargetClassify());
                        map.put("icon", StringUtils.isNotBlank(only.getIcon()) ? this.keyWordSystem.getSERVER_URL() + only.getIcon() : null);
                        resultList.add(map);
                    }
                }
                resultMap.put("targetList", resultList);
                resultMap.put("pageNum", 1);
                resultMap.put("pageSize", 10);
                resultMap.put("total", resultList.size());
                resultMap.put("pageAll", 1);
            }
            return ResultUtil.success("查询成功", resultMap);
        }
        return ResultUtil.error(ResultEnum.TYPE_ID_EMPTY);
    }

    @Override
    public void addCommonCountry(List<String> country) {
        int max = 20;
        Set<Object> set = null;
        if (redisUtil.hasKey(keyWordSystem.getVERSION() + "common")) {
            set = redisUtil.sGet(keyWordSystem.getVERSION() + "common");
            redisUtil.del(keyWordSystem.getVERSION() + "common");
        }
        int count = country.size();
        if (count > max) {
            count = max;
        }
        Set<Object> common = new TreeSet<>();
        for (int i = 0; i < count; i++) {
            common.add(country.get(i));
        }
        if (null != set && count < max) {
            count = max - country.size() > set.size() ? set.size() : max - country.size();
            for (Object o : set) {
                if (count == 0) {
                    break;
                }
                common.add(o);
                count--;
            }
        }
        redisUtil.sSet(keyWordSystem.getVERSION() + "common", common.toArray());
    }

    @Override
    public synchronized Result getCommonSort(String id, int sign) {
        CommonAttribute commonSort = commonMapper.findCommonSort(id);
        if (null != commonSort) {
            if (commonSort.getId().length() == 3) {
                return ResultUtil.error(500, "默认属性不能移动");
            }
            Map<String, Object> map = null;
            switch (sign) {
                case 1:
                    map = commonMapper.getMin(commonSort.getSign());
                    if (null == map || map.get("id").equals(commonSort.getId())) {
                        return ResultUtil.error(500, "已经上移到最顶");
                    } else {
                        if (commonSort.getSign() == 1) {
                            if (commonSort.getSort() == 2) {
                                return ResultUtil.error(500, "已经上移到最顶");
                            }
                            commonMapper.updateCommonSort(commonSort.getId(), 2);
                        } else {
                            if (commonSort.getSort() == 3) {
                                return ResultUtil.error(500, "已经上移到最顶");
                            }
                            commonMapper.updateCommonSort(commonSort.getId(), 3);
                        }
                        List<CommonAttribute> commonSortSign = commonMapper.findCommonSortSign(commonSort.getSign());
                        for (CommonAttribute commonAttribute : commonSortSign) {
                            if (commonAttribute.getId().equals(commonSort.getId()) || commonAttribute.getId().length() == 3) {
                                continue;
                            }
                            commonAttribute.setSort(commonAttribute.getSort() + 1);
                            commonMapper.updateCommonSort(commonAttribute.getId(), commonAttribute.getSort());
                        }
                    }
                    break;
                case 2:
                    map = commonMapper.getUp(commonSort.getSort(), commonSort.getSign());
                    if (null == map || map.get("id").toString().length() == 3) {
                        return ResultUtil.error(500, "已经上移到最顶");
                    } else {
                        commonMapper.updateCommonSort(commonSort.getId(), (Integer) map.get("sort"));
                        commonMapper.updateCommonSort(map.get("id").toString(), commonSort.getSort());
                    }
                    break;
                case 3:
                    map = commonMapper.getDown(commonSort.getSort(), commonSort.getSign());
                    if (null == map) {
                        return ResultUtil.error(500, "已经下移到最底");
                    } else {
                        commonMapper.updateCommonSort(commonSort.getId(), (Integer) map.get("sort"));
                        commonMapper.updateCommonSort(map.get("id").toString(), commonSort.getSort());
                    }
                    break;
                case 4:
                    map = commonMapper.getMax(commonSort.getSign());
                    if (null == map || map.get("id").equals(commonSort.getId())) {
                        return ResultUtil.error(500, "已经下移到最底");
                    } else {
                        commonMapper.updateCommonSort(commonSort.getId(), commonMapper.getCommonMaxSort(commonSort.getSign()) + 1);
                    }
                    break;
            }
            return ResultUtil.success("操作成功", null);
        }
        return ResultUtil.error(ResultEnum.TYPE_EMPTY);
    }

    @Override
    public Result addRadius(String id, Double radius) {
        zoneMapper.addTypeElse(id, radius);
        return ResultUtil.success();
    }

    @Override
    public Result getRadius(String id) {
        return ResultUtil.success(FileElseUtil.getStringTransitionDouble(zoneMapper.getTypeElse(id)));
    }

    @Override
    public void initTypeSign() {
        List<Map<String, String>> typeSign = zoneMapper.getInitTypeSign();
        if (CollectionUtil.isNotEmpty(typeSign)) {
            for (Map<String, String> map : typeSign) {
                if (ObjectUtil.isEmpty(map.get("icon"))) {
                    zoneMapper.addSign(map.get("id"), "default.png");
                    redisUseService.updateTypeSign(map.get("id"), "default.png");
                }
            }
        }
    }

    @Override
    public Result getCountryList(String country, String level) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<String> levels = null;
        Map<String, Object> map = null;
        if (StringUtils.isBlank(country) && StringUtils.isBlank(level)) {
            List<Object> list = redisUtil.lGet(this.keyWordSystem.getVERSION() + "-REGION", 0, -1);
            if (ObjectUtil.isNotEmpty(list)) {
                return ResultUtil.success(list);
            }
        } else if (StringUtils.isNotBlank(country) && StringUtils.isNotBlank(level)) {
            Zone zone = zoneMapper.getZoneByName(country);
            if (ObjectUtil.isNotEmpty(zone)) {
                List<Zone> zoneElse = null;
                map = new HashMap<>();
                map.put("value", zone.getAdcode());
                map.put("label", zone.getName());
                Region region = regionMapper.getRegionOne(zone.getAdcode());
                if (ObjectUtil.isNotEmpty(region)) {
                    map.put("region", region.getGeometry());
                } else {
                    map.put("region", new HashMap<>());
                }
                map.put("center", Arrays.asList(zone.getLng(), zone.getLat(), 0));
                switch (level) {
                    case "province":
                        zoneElse = zoneMapper.getZoneAll(Arrays.asList("city", "district"));
                        break;
                    case "city":
                        zoneElse = zoneMapper.getZoneAll(Arrays.asList("district"));
                        break;
                    default:
                        break;
                }
                if (CollectionUtil.isNotEmpty(zoneElse)) {
                    map.put("children", getTreeChild(zone.getAdcode(), zoneElse));
                } else {
//                    map.put("children", new ArrayList<>());
                }
                resultList.add(map);
            }
        }
        return ResultUtil.success(resultList);
    }

    @Override
    public Result getRegionAndCenter(String adcode, String country) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isNotBlank(adcode)) {
            Zone zone = zoneMapper.getZoneByAdcode(adcode);
            if (ObjectUtil.isNotEmpty(zone)) {
                resultMap.put("center", Arrays.asList(zone.getLng(), zone.getLat(), 0));
            } else {
                resultMap.put("center", new ArrayList<>());
            }
            Region region = regionMapper.getRegionOne(adcode);
            if (ObjectUtil.isNotEmpty(region)) {
                resultMap.put("region", region.getGeometry());
            } else {
                resultMap.put("region", new HashMap<>());
            }
        } else if (StringUtils.isNotBlank(country)) {
            Zone zone = zoneMapper.getZoneByName(country);
            if (ObjectUtil.isNotEmpty(zone)) {
                resultMap.put("center", Arrays.asList(zone.getLng(), zone.getLat(), 0));
                Region region = regionMapper.getRegionOne(zone.getAdcode());
                if (ObjectUtil.isNotEmpty(region)) {
                    resultMap.put("region", region.getGeometry());
                } else {
                    resultMap.put("region", new HashMap<>());
                }
            } else {
                resultMap.put("center", new ArrayList<>());
                resultMap.put("region", new HashMap<>());
            }
        } else {
            resultMap.put("center", new ArrayList<>());
            resultMap.put("region", new HashMap<>());
        }
        return ResultUtil.success(resultMap);
    }

    @Override
    public void initFontData() {
        List<FontTable> list = fontTableService.list();
        if (CollectionUtil.isEmpty(list)) {
            {
                FontTable fontTable = new FontTable();
                fontTable.setFontName("体系名称");
                fontTable.setFontSize(52);
                fontTable.setFontColor("rgba(242, 212, 19, 1)");
                fontTableService.save(fontTable);
                redisUseService.updateFont("体系名称", JSON.toJSONString(fontTable));
            }
            {
                FontTable fontTable = new FontTable();
                fontTable.setFontName("作用范围名称");
                fontTable.setFontSize(28);
                fontTable.setFontColor("rgba(20, 249, 242, 1)");
                fontTableService.save(fontTable);
                redisUseService.updateFont("作用范围名称", JSON.toJSONString(fontTable));
            }
        } else {
            for (FontTable fontTable : list) {
                redisUseService.updateFont(fontTable.getFontName(), JSON.toJSONString(fontTable));
            }
        }
    }

    @Override
    public Result updateFont(JSONObject json) {
        String fontName = json.getString("fontName");
        Integer fontSize = json.getInteger("fontSize");
        String fontColor = json.getString("fontColor");
        if (StringUtils.isBlank(fontName) || null == fontSize || StringUtils.isBlank(fontColor)) {
            return ResultUtil.error(500, "数据不能为空，请检查后重试");
        }
        FontTable fontTable = fontTableService.lambdaQuery().eq(FontTable::getFontName, fontName).one();
        if (ObjectUtil.isNull(fontTable)) {
            fontTable = new FontTable();
        }
        fontTable.setFontName(fontName);
        fontTable.setFontSize(fontSize);
        fontTable.setFontColor(fontColor);
        fontTableService.saveOrUpdate(fontTable);
        redisUseService.updateFont(fontTable.getFontName(), JSON.toJSONString(fontTable));
        return ResultUtil.success();
    }

    @Override
    public Result getFont(JSONObject json) {
        String fontName = json.getString("fontName");
        if (StringUtils.isNotBlank(fontName)) {
            FontTable fontTable = fontTableService.lambdaQuery().eq(FontTable::getFontName, fontName).one();
            if (ObjectUtil.isNull(fontTable)) {
                fontTable = new FontTable();
                fontTable.setFontName(FileElseUtil.getObjectToString(fontName));
                if (StringUtils.isNotBlank(fontName) && "体系名称".equals(fontName)) {
                    fontTable.setFontSize(5);
                } else {
                    fontTable.setFontSize(28);
                }
                fontTable.setFontColor("rgba(20, 249, 242, 1)");
            }
            return ResultUtil.success(fontTable);
        } else {
            List<FontTable> list = fontTableService.list();
            return ResultUtil.success(CollectionUtil.isNotEmpty(list) ? list : ListUtil.empty());
        }
    }

    private boolean judgeParamName(String name) {
        String[] strs = {"targetName", "targetClassify", "country", "lon", "lat",
                "height", "subName", "shape", "width", "radius", "innerRadius", "outRadius",
                "angle", "earthHeight", "crucial", "heights",
                "viewDistances", "length", "texture", "plotinfoobj", "position", "icon",
                "mbRadioValue", "mbRadioType"};
        for (String str : strs) {
            if (name.toLowerCase().equals(str)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 递归查询国家树
     *
     * @param id
     * @param allTree
     * @return
     */
    private List<Map<String, Object>> getTreeChild(String id, List<Zone> allTree) {
        /**
         * 子菜单
         */
        List<Map<String, Object>> childList = new ArrayList<>();
        for (Zone zone : allTree) {
            if (StringUtils.isNotBlank(zone.getParent())) {
                if (id.equals(zone.getParent())) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("value", zone.getAdcode());
                    map.put("label", zone.getName());
                    map.put("region", new HashMap<>());
                    map.put("center", new ArrayList<>());
                    childList.add(map);
                }
            }
        }
        /**
         * 递归
         */
        for (Map<String, Object> map : childList) {
            String aId = (String) map.get("value");
            List<Map<String, Object>> child = getTreeChild(aId, allTree);
            if (CollectionUtil.isNotEmpty(child)) {
                map.put("children", getTreeChild(aId, allTree));
            }
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    private void mainCommon(List<Map<String, Object>> list) {
        {
            Map<String, Object> map = new HashMap<>();
            map.put("id", "100001");
            map.put("keyName", "作用范围半径");
            map.put("key", "mbRadioValue");
            map.put("keyType", "Double");
            map.put("showType", "text");
            map.put("required", "false");
            map.put("info", "false");
            map.put("dataRange", "");
            map.put("verify", "false");
            map.put("min", "");
            map.put("max", "");
            map.put("enumerator", ListUtil.empty());
            map.put("row", "");
            map.put("message", "");
            list.add(map);
        }
        {
            Map<String, Object> map = new HashMap<>();
            map.put("id", "100002");
            map.put("keyName", "作用范围类型");
            map.put("key", "mbRadioType");
            map.put("keyType", "list");
            map.put("showType", "select");
            map.put("required", "false");
            map.put("info", "false");
            map.put("dataRange", "");
            map.put("verify", "false");
            map.put("min", "");
            map.put("max", "");
            List<Map<String, Object>> resultList = new ArrayList<>();
            List<RangeType> rangeTypes = rangeTypeMapper.selectList(null);
            if (CollectionUtil.isNotEmpty(rangeTypes)) {
                Map<String, Object> m;
                for (RangeType rangeType : rangeTypes) {
                    m = new HashMap<>();
                    m.put("value", rangeType.getId());
                    m.put("label", rangeType.getName());
                    resultList.add(m);
                }
            }
            map.put("enumerator", resultList);
            map.put("row", "");
            map.put("message", "");
            list.add(map);
        }
    }

}